<?php
namespace app\controllers;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\Queue;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class MonthController extends Controller
{
    protected $set;

    // 每月1号5点执行
    // 0 5 1 * * /usr/bin/curl http://http://j2-api.97app.cn/month
    // public function actionIndex()
    // {
    //     $month = date('Ym');
    //     $month = intval($month);
    //
    //     // 检查是否已返
    //     $is = Queue::find()
    //         ->where(['month' => $month])
    //         ->andWhere(['status' => 1])
    //         ->one();
    //     if ($is) {
    //         return '已返';
    //     }
    //
    //     // 处理佣金
    //     $list = $this->go();
    //     // var_dump($list);exit;
    //
    //     foreach ($list as $item) {
    //         $commission = $this->commissionCalc($list, $item);
    //         // echo $commission, "<br>";
    //
    //         // 可能出现负
    //         if ($commission <= 0) {
    //             $commission = 0;
    //         }
    //
    //         $this->saveCommission($item['id'], $commission, '99', '分红奖');
    //     }
    //
    //     // 保存已返状态
    //     $queue = Queue::findOne(['month' => $month]);
    //     if (!$queue) {
    //         $queue = new Queue();
    //         $queue->month = $month;
    //     }
    //     $queue->status = 1;
    //     $queue->save();
    //
    //     echo $month;
    // }

    // protected function saveCommission($user_id, $balance, $type, $name)
    // {
    //     if ($balance > 0) {
    //         $model = new UserCommission();
    //         $model->user_id = $user_id;
    //         $model->fans_id = 0;
    //         $model->order_id = 0;
    //         $model->balance = $balance;
    //         $model->status = 1;
    //         $model->award_name = $name;
    //         $model->award_type = $type;
    //         $model->save();
    //
    //         $account = UserAccount::findOne(['user_id' => $user_id]);
    //         if ($account) {
    //             $account->balance += $balance;
    //             $account->save();
    //         }
    //     }
    // }

    // public function go($referrer_id = 0, $list = [])
    // {
    //     $query = User::find();
    //     if ($referrer_id > 0) {
    //         $query->where(['id' => $referrer_id]);
    //     } else {
    //         // $query->where(['referrer_id' => $referrer_id]);
    //         // 第1批
    //         $query->andWhere(['level' => [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]]);
    //     }
    //
    //     $users = $query->andWhere(['level' => [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]])
    //         ->orderBy(['id' => SORT_ASC])
    //         ->select(['id'])
    //         ->asArray()
    //         ->all();
    //
    //     // 第1批, 筛选(不能是别人的管理)
    //     if ($referrer_id == 0) {
    //         $tmp = [];
    //         foreach ($users as $u) {
    //             $chain = Chain::getReferrerChain($u['id'], [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]);
    //             if ($chain) {
    //                 continue;
    //             }
    //             array_push($tmp, $u);
    //         }
    //         $users = $tmp;
    //     }
    //
    //     $users = ArrayHelper::getColumn($users, 'id');
    //
    //     // 2) 团队
    //     $team = [];
    //     foreach ($users as $user) {
    //
    //         // 全部
    //         $children = Chain::getChildrenAllQuick($user, [
    //             UserLevel::$keys['vip1'],
    //             UserLevel::$keys['vip2'],
    //             UserLevel::$keys['svip1'],
    //             UserLevel::$keys['svip2'],
    //         ], ['id']);
    //         $children = ArrayHelper::getColumn($children, 'id');
    //
    //         // 管理
    //         $manager = Chain::getChildrenAllQuick($user, [
    //             UserLevel::$keys['svip2'],
    //             UserLevel::$keys['svip1'],
    //         ], ['id']);
    //
    //         $manager = ArrayHelper::getColumn($manager, 'id');
    //
    //         $team[] = [
    //             'id' => $user,
    //             'children' => $children,
    //             'manager' => $manager
    //         ];
    //     }
    //
    //     $users = $team;
    //
    //     // 3) 业绩
    //     foreach ($users as $user) {
    //         $orders = Order::find()
    //             ->where(['user_id' => array_merge([$user['id']], $user['children'])])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
    //             // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
    //             // 上个月的 (下个月1号返)
    //             // ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
    //             // todo 这里是累计的, 每个月返1次就行了
    //             ->all();
    //
    //         $sum = 0;
    //         foreach ($orders as $order) {
    //             $sum += $order->total_pay;
    //         }
    //
    //         $user['sum'] = $sum;
    //         $user['amount'] = $this->getAmount($sum);
    //
    //         if (!key_exists($user['id'], $list)) {
    //             $list[$user['id']] = $user;
    //         }
    //
    //         // // 子团队业务
    //         foreach ($user['manager'] as $item) {
    //             $list = $this->go($item, $list);
    //         }
    //
    //     }
    //
    //     return $list;
    // }

    // protected function getAmount($sum)
    // {
    //     if ($sum == 0) {
    //         return 0;
    //     }
    //
    //     $model = ZSetting::find()
    //         ->where(['<=', 'start', $sum])
    //         ->andWhere(['>=', 'end', $sum])
    //         ->one();
    //
    //     // echo $model->createCommand()->getRawSql();exit;
    //
    //     if ($model) {
    //         return $model->amount;
    //     }
    //
    //     // 最大
    //     $last = ZSetting::find()
    //         ->orderBy(['amount' => SORT_DESC])
    //         ->one();
    //     if ($sum >= $last->end) {
    //         return $last->amount;
    //     }
    //
    //     return 0;
    // }

    // public function commissionCalc($list, $item)
    // {
    //     // 找出需要减掉的(可能有多个)
    //     $data = [];
    //     foreach ($item['manager'] as $v) {
    //         $chain = Chain::getReferrerChain($v, [UserLevel::$keys['svip2'], UserLevel::$keys['svip1']]);
    //         if ($chain) {
    //
    //             if ($chain[0]['id'] == $item['id']) {
    //                 array_push($data, $v);
    //             }
    //         }
    //     }
    //
    //     // var_dump($data);exit;
    //
    //     $sub = 0;
    //     foreach ($list as $v) {
    //         if (in_array($v['id'], $data)) {
    //             $sub += $v['amount'];
    //         }
    //     }
    //
    //     return $item['amount'] - $sub;
    // }

    // 山东月奖
    /*
     * 每月1号 4点
     * 0 4 1 * * /usr/bin/curl https://api.sxjk888.top/month/sd
     */
    public function actionSd()
    {
        $transaction = \Yii::$app->db->beginTransaction();

        $this->set = SetUserUp::getLastOne();

        try {
            $queue = Queue::find()
                ->where(['status' => 0])
                // 上个月的
                ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                ->orderBy(['id' => SORT_ASC])
                ->all();

            // var_dump($queue);exit;

            foreach ($queue as $item) {
                $order = Order::findOne(['id' => $item->order_id]);
                if (!$order) {
                    continue;
                }

                $log = $order->log;
                if (!$log) {
                    continue;
                }

                $log = json_decode($log, true);
                $chain = $log['chain'];
                if (!$chain) {
                    continue;
                }

                // var_dump($chain);exit;

                // 找出第1个区域
                foreach ($chain as $user) {
                    if ($user['level'] == UserLevel::$keys['svip2']) {

                        // var_dump($user);exit;

                        // 1) 必须直推3个区代
                        $count = User::find()
                            ->where(['referrer_id' => $user['id']])
                            ->andWhere(['level' => UserLevel::$keys['svip2']])
                            ->count();

                        // var_dump($count, $this->set->address_num);exit;

                        if (intval($count) >= $this->set->address_num) {

                            // var_dump($user['id']);exit;

                            // 2) 业绩部门中不能有超过50%的
                            $isOut = $this->isOut($user['id']);
                            // var_dump($isOut);exit;

                            if (!$isOut) {

                                $this->_profit($user, $order);

                            }

                            // 如果是一个一个找
                            // break;
                        }

                        // 只处理团队中第1个
                        break;

                    }
                }

                $item->status = 1;
                $item->save();

            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
    }

    protected function saveCommission($user_id, $balance, $type, $name, $text = '返佣', $status = 0, $order_id = 0, $fans_id = 0)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }
                $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, $text, $order_id);
            }
        }
    }

    private function _profit($user, Order $order)
    {
        $u = User::findOne(['id' => $user['id']]);
        if ($u) {
            $box = $this->getBox($order);
            // 如果按订单算, 则把盒数改成1
            // $box = 1;

            // var_dump($box);exit;

            $commission = $this->set->address_award * $box;

            // var_dump($commission);exit;

            // 公司出钱
            // $this->money += $commission;

            $this->saveCommission($u['id'], $commission, 88, '分红', '分红', 1, $order->id, $order->user_id);
        }

    }

    protected function getBox(Order $order)
    {
        // 如果订单有保存盒数, 则从订单从来
        // if ($this->order->is_store == 1 && $this->order->store_box > 0) {
        //     return $this->order->store_box;
        // }

        if ($order->is_store == 1 && $order->store_box > 0) {
            return $order->store_box;
        }

        // 否则从产品中算 (可能产品有改动)
        $items = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->with(['product'])
            ->all();
        $box = 0;
        foreach ($items as $item) {
            if ($item['product']) {
                $box += $item['product']['store'] * $item['quantity'];
            }
        }

        return  $box;
    }

    private function isOut($user_id)
    {
        $total_ids = Chain::getChildrenAllQuick($user_id, [], ['id']);
        $total_ids = ArrayHelper::getColumn($total_ids, 'id');
        $total_ids = array_merge([$user_id], $total_ids);

        $child_svip2 = User::find()
            ->where(['referrer_id' => $user_id])
            ->andWhere(['level' => UserLevel::$keys['svip2']])
            ->select(['id'])
            ->column();

        // var_dump($total_ids, $child_svip2);exit;

        // 总业绩
        $total_box = $this->boxByOrder($total_ids);
        if ($total_box == 0) {
            return false;
        }

        // var_dump($total_box);exit;

        // 判断部门业绩
        foreach ($child_svip2 as $id) {
            $child = Chain::getChildrenAllQuick($id, [], ['id']);
            $child = ArrayHelper::getColumn($child, 'id');
            $child = array_merge([$id], $child);
            $box = $this->boxByOrder($child);

            // echo $id, ' -> ', $box, ' - ';
            // continue;

            // 如果部门没有业绩, 可以设置不返
            if ($box == 0) {
                return true;
            }

            // 是否大于50%
            if ($box / $total_box >= 0.5) {
                return true;
            }
        }

        // exit;

        return false;
    }

    private function boxByOrder($ids)
    {
        $orders = Order::find()
            ->where(['user_id' => $ids])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            // 提货的不算
            ->andWhere(['is_extract' => 0])
            ->select(['id'])
            ->column();

        // var_dump($orders);exit;

        $items = OrderItem::find()
            ->where(['order_id' =>$orders])
            ->with(['product'])
            ->all();
        $box = 0;
        foreach ($items as $item) {
            if ($item['product']) {

                // 84000 不算
                if ($item['product']['price'] == 84000) {
                    continue;
                }

                $box += $item['product']['store'] * $item['quantity'];
            }
        }

        return  $box;
    }
}